package com.kuangstudy.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.kuangstudy.constant.RedisConstants;
import com.kuangstudy.entity.User;
import com.kuangstudy.mapper.UserMapper;
import com.kuangstudy.utils.bean.BeanMapUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author panghu
 * @version 1.0.0
 * @createTime 2023年09月16日 18:13:00
 * @Description
 */
@RestController
@Api(tags = "用户注册相关")
public class RegController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserMapper userMapper;

    @PostMapping("/user/reg")
    @ApiOperation("用户注册方法")
    public String regUser(@RequestBody User user) {
        // 根据用户名 先去数据库查询该用户是否存在
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getNickName,user.getNickName());
        User userInfo = userMapper.selectOne(lambdaQueryWrapper);

        // 如果用户存在抛出异常
        if (Objects.nonNull(userInfo) ) {
            throw new RuntimeException("该用户已经注册过啦...");
        }

        // 如果用户不存在把用户注册到DB中
        userMapper.insert(user);

        // 然后把用户信息放入到hash中缓存起来
        String redisKey = RedisConstants.REG_USER_HASH + user.getId();
        Map<String, Object> userMap = BeanMapUtils.beanToMap(user);
        redisTemplate.opsForHash().putAll(redisKey, userMap);

        // 设置key的失效时间一个月
        // 设置过期时间的作用：防止用户注册以后不使用任何服务，也就是所谓的僵尸粉，不设置过期时间造成内存的浪费大可不必
        redisTemplate.expire(redisKey, 30, TimeUnit.DAYS);
        return "success";
    }

}
